<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="MongoDB 查询文档使用 find() 方法。find() 方法以非结构化的方式来显示所有文档。">
<meta name="keywords" content="MongoDB,数据库">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB-查找操作">
<meta property="og:url" content="https://rencheng.cc/2019/08/11/mongodb/查找操作/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="MongoDB 查询文档使用 find() 方法。find() 方法以非结构化的方式来显示所有文档。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-08-11T03:50:14.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB-查找操作">
<meta name="twitter:description" content="MongoDB 查询文档使用 find() 方法。find() 方法以非结构化的方式来显示所有文档。">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2019/08/11/mongodb/查找操作/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>MongoDB-查找操作 | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2019/08/11/mongodb/查找操作/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">MongoDB-查找操作

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-08-11 11:50:14" itemprop="dateCreated datePublished" datetime="2019-08-11T11:50:14+08:00">2019-08-11</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/教程/" itemprop="url" rel="index"><span itemprop="name">教程</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">5.6k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>MongoDB 查询文档使用 find() 方法。find() 方法以非结构化的方式来显示所有文档。</p>
<a id="more"></a>
<h2 id="find"><a href="#find" class="headerlink" title="find"></a>find</h2><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.find</span>(query,field)</span><br></pre></td></tr></table></figure>
<ul>
<li>功能 ：   查找文档</li>
<li>参数 <ul>
<li>query  查找条件，相当于where子句</li>
<li>field  查找的域</li>
</ul>
</li>
<li>返回值 ： 查找到的所有文档</li>
</ul>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">query</span>：  以键值对方式传递参数，如果是空&#123;&#125;表示查找所          有内容</span><br><span class="line"></span><br><span class="line">  <span class="selector-tag">e</span><span class="selector-class">.g</span>.   查找所有性别为<span class="selector-tag">w</span>的文档  </span><br><span class="line">         <span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">sex</span>:<span class="string">'w'</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="selector-tag">field</span>：  以键值对的方式给出要查找（不查找）的域</span><br><span class="line">        以域名为键，以0,1为值分别表示不查找和查找</span><br></pre></td></tr></table></figure>
<ul>
<li>如果某一个或多个域设置为0 表示这些域不查找，其他域均查找</li>
<li>如果某一个或多个域设置为1 表示这些域查找，其他域均不查找</li>
<li><code>_id</code> 除非设置为0 否则均会查找</li>
<li>除<code>_id</code>域其他域不能有的设置1有的设置0</li>
</ul>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>. 查找结果只有<span class="selector-tag">name</span>域</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">sex</span>:<span class="string">'w'</span>&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>,name:<span class="number">1</span>&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="findOne"><a href="#findOne" class="headerlink" title="findOne"></a>findOne</h2><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">findOne</span><span class="params">(query,field)</span></span></span><br></pre></td></tr></table></figure>
<ul>
<li>功能 ： 查找第一条符合条件的文档</li>
<li>参数 ： 同find</li>
<li>返回值： 返回查找到的文档</li>
</ul>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>. 查找集合中性别为女的第一个文档</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.findOne</span>(&#123;<span class="attribute">sex</span>:<span class="string">'w'</span>&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>,name:<span class="number">1</span>&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="query更多的筛选用法"><a href="#query更多的筛选用法" class="headerlink" title="query更多的筛选用法"></a>query更多的筛选用法</h2><p>操作符 ： 使用<code>$</code>符号注明的一个特殊字符串，表达一定的含义，比如 <code>$lt</code> 表示小于</p>
<h3 id="比较操作符"><a href="#比较操作符" class="headerlink" title="比较操作符"></a>比较操作符</h3><h4 id="eq-等于"><a href="#eq-等于" class="headerlink" title="$eq 等于 =="></a><em>$eq</em> 等于 ==</h4><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">e<span class="selector-class">.g</span>. 查找年龄等于<span class="number">18</span></span><br><span class="line">db<span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;age:&#123;<span class="variable">$eq</span>:<span class="number">18</span>&#125;&#125;,&#123;_id:<span class="number">0</span>&#125;)</span><br><span class="line">==&gt; db<span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;age:<span class="number">18</span>&#125;,&#123;_id:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="lt-小于-lt"><a href="#lt-小于-lt" class="headerlink" title="$lt 小于 &lt;"></a><em>$lt</em> 小于 &lt;</h4><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>. 查找年龄小于18的</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">age</span>:&#123;$lt:<span class="number">18</span>&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">name</span>:&#123;$lt:<span class="string">"John"</span>&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在mongodb中字符串可以比较大小</p>
</blockquote>
<h4 id="lte-小于等于-lt"><a href="#lte-小于等于-lt" class="headerlink" title="$lte  小于等于 &lt;="></a><em>$lte</em>  小于等于 &lt;=</h4><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  年龄小于等于18 </span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">age</span>:&#123;$lte:<span class="number">18</span>&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="gt-大于-gt"><a href="#gt-大于-gt" class="headerlink" title="$gt  大于 &gt;"></a><em>$gt</em>  大于 &gt;</h4><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  查找年龄大于16 且 小于19</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">age</span>:&#123;$gt:<span class="number">16</span>,$lt:<span class="number">19</span>&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在mongodb中所有的{} [] 中都可以写多个条件。但根据   参数的不同表达的意思不一样</p>
</blockquote>
<h4 id="gte-大于等于-gt"><a href="#gte-大于等于-gt" class="headerlink" title="$gte 大于等于 &gt;="></a><em>$gte</em> 大于等于 &gt;=</h4><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  大于等于19</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">age</span>:&#123;$gte:<span class="number">19</span>&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="ne-不等于"><a href="#ne-不等于" class="headerlink" title="$ne  不等于  !="></a><em>$ne</em>  不等于  !=</h4><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  性别不等于‘<span class="selector-tag">m</span>’的 </span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">sex</span>:&#123;$ne:<span class="string">'m'</span>&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>使用ne查找也会找到该域不存在的文档</p>
</blockquote>
<h4 id="in-包含"><a href="#in-包含" class="headerlink" title="$in  包含"></a><em>$in</em>  包含</h4><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>. 找到年龄为 <span class="selector-attr">[10,20,30]</span></span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">age</span>:&#123;$in:[<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>]&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="nin-不包含"><a href="#nin-不包含" class="headerlink" title="$nin 不包含"></a><em>$nin</em> 不包含</h4><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  找到年龄不是 17  18   19 的</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">age</span>:&#123;$nin:[<span class="number">17</span>,<span class="number">18</span>,<span class="number">19</span>]&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="逻辑操作符"><a href="#逻辑操作符" class="headerlink" title="逻辑操作符"></a>逻辑操作符</h3><h4 id="and-逻辑与"><a href="#and-逻辑与" class="headerlink" title="$and 逻辑与"></a><em>$and</em> 逻辑与</h4><ol>
<li>在 query 如果写多个条件默认即为 and 关系</li>
</ol>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">age</span>:&#123;$lt:<span class="number">18</span>&#125;,<span class="selector-tag">sex</span><span class="selector-pseudo">:'m'</span>&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<ol>
<li>逻辑与 $and</li>
</ol>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">e<span class="selector-class">.g</span>. 年龄小于<span class="number">18</span>并且 性别为男</span><br><span class="line">db<span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="variable">$and</span>:[&#123;age:&#123;<span class="variable">$lt</span>:<span class="number">18</span>&#125;&#125;,&#123;sex:<span class="string">'m'</span>&#125;]&#125;,&#123;_id:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>区别： 第一种不能对相同的域进行操作</p>
</blockquote>
<h4 id="or-逻辑或"><a href="#or-逻辑或" class="headerlink" title="$or  逻辑或"></a><em>$or</em>  逻辑或</h4><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">e<span class="selector-class">.g</span>. 年龄小于<span class="number">16</span>或者年龄大于<span class="number">18</span></span><br><span class="line">db<span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="variable">$or</span>:[&#123;age:&#123;<span class="variable">$lte</span>:<span class="number">16</span>&#125;&#125;,&#123;age:&#123;<span class="variable">$gt</span>:<span class="number">18</span>&#125;&#125;]&#125;,&#123;_id:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="not-逻辑非"><a href="#not-逻辑非" class="headerlink" title="$not  逻辑非"></a><em>$not</em>  逻辑非</h4><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  查找年龄不小于18岁的</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">age</span>:&#123;$not:&#123;$lt:<span class="number">18</span>&#125;&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>非运算并不是正常运算取反<br>age &lt; 18 不等于 not[age &lt; 18]<br>是因为mongo过于灵活，某个域的值的类型不一致</p>
</blockquote>
<h4 id="nor-not-a-or-b-gt-not-a-and-not-b"><a href="#nor-not-a-or-b-gt-not-a-and-not-b" class="headerlink" title="$nor   not  (a or b)  ===&gt; (not a) and (not b)"></a><em>$nor</em>   not  (a or b)  ===&gt; (not a) and (not b)</h4><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">e<span class="selector-class">.g</span>.  性别不是m且年龄不小于<span class="number">18</span></span><br><span class="line">db<span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="variable">$nor</span>:[&#123;sex:<span class="string">'m'</span>&#125;,&#123;age:&#123;<span class="variable">$lt</span>:<span class="number">18</span>&#125;&#125;]&#125;,&#123;_id:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="逻辑条件混合"><a href="#逻辑条件混合" class="headerlink" title="逻辑条件混合"></a>逻辑条件混合</h4><figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">（年龄大于<span class="number">17</span> 并且 为男生）  或者 姓名叫 Abby</span><br><span class="line"> db.class0.find(&#123;<span class="string">$or:</span>[&#123;<span class="string">age:</span>&#123;<span class="string">$gt:</span><span class="number">17</span>&#125;,<span class="string">sex:</span><span class="string">'m'</span>&#125;,&#123;<span class="string">name:</span><span class="string">'Abby'</span>&#125;]&#125;,&#123;<span class="string">_id:</span><span class="number">0</span>&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">（年龄不大于<span class="number">18</span> 或者为 女性） 并且 姓名 大于Lucy</span><br><span class="line"> e.g.</span><br><span class="line"> db.class0.find(&#123;<span class="string">$or:</span>[&#123;<span class="string">age:</span>&#123;<span class="string">$not:</span>&#123;<span class="string">$gt:</span><span class="number">18</span>&#125;&#125;&#125;,&#123;<span class="string">sex:</span><span class="string">'w'</span>&#125;],<span class="string">name:</span>&#123;<span class="string">$gt:</span><span class="string">'Lucy'</span>&#125;&#125;,&#123;<span class="string">_id:</span><span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="数组-Array"><a href="#数组-Array" class="headerlink" title="数组 Array"></a>数组 Array</h3><ul>
<li>数组是有序的数据集合</li>
<li>mongo中数组也可以有多重数据元素混合</li>
</ul>
<p>查找数组中包含某一条件的元素<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  只要<span class="selector-tag">score</span>数组中包含小于60的元素即可查询过滤</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class1</span><span class="selector-class">.find</span>(&#123;<span class="attribute">score</span>:&#123;$lt:<span class="number">60</span>&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure></p>
<h4 id="all"><a href="#all" class="headerlink" title="$all"></a>$all</h4><p>查找数组同时包含多项的文档<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  查找同时包含49  67的文档</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class1</span><span class="selector-class">.find</span>(&#123;<span class="attribute">score</span>:&#123;$all:[<span class="number">49</span>,<span class="number">67</span>]&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure></p>
<h4 id="size"><a href="#size" class="headerlink" title="$size"></a>$size</h4><p>通过数组元素个数查找<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>. 查找<span class="selector-tag">score</span>中包含两个元素的文档</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class1</span><span class="selector-class">.find</span>(&#123;<span class="attribute">score</span>:&#123;$size:<span class="number">2</span>&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure></p>
<h4 id="slice"><a href="#slice" class="headerlink" title="$slice"></a>$slice</h4><p>取数组的部分进行显示，在<code>field</code>中声明<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  显示数组中前两项</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class2</span><span class="selector-class">.find</span>(&#123;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>,score:&#123;$slice:<span class="number">2</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.   跳过第一项显示后面两项</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class2</span><span class="selector-class">.find</span>(&#123;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>,score:&#123;$slice:[<span class="number">1</span>,<span class="number">2</span>]&#125;&#125;)</span><br></pre></td></tr></table></figure></p>
<h3 id="其他常用查找操作符"><a href="#其他常用查找操作符" class="headerlink" title="其他常用查找操作符"></a>其他常用查找操作符</h3><h4 id="exists"><a href="#exists" class="headerlink" title="$exists"></a>$exists</h4><p>通过某个域是否存在筛选（true表示存在false表示不存在）<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>. ： 查找不存在<span class="selector-tag">sex</span>域的文档</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class1</span><span class="selector-class">.find</span>(&#123;<span class="attribute">sex</span>:&#123;$exists:false&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure></p>
<h4 id="mod"><a href="#mod" class="headerlink" title="$mod"></a>$mod</h4><p>余数查找<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  找出年龄为单数的文档</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class1</span><span class="selector-class">.find</span>(&#123;<span class="attribute">age</span>:&#123;$mod:[<span class="number">2</span>,<span class="number">1</span>]&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure></p>
<h4 id="type"><a href="#type" class="headerlink" title="$type"></a>$type</h4><p>找出指定数据类型的文档<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  查找<span class="selector-tag">name</span>域值类型为2的文档</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class1</span><span class="selector-class">.find</span>(&#123;<span class="attribute">name</span>:&#123;$type:<span class="number">2</span>&#125;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)</span><br></pre></td></tr></table></figure></p>
<h4 id="regex"><a href="#regex" class="headerlink" title="$regex"></a>$regex</h4><p>找出指定正则的文档</p>
<h3 id="查找结果的操作函数"><a href="#查找结果的操作函数" class="headerlink" title="查找结果的操作函数"></a>查找结果的操作函数</h3><h4 id="distinct"><a href="#distinct" class="headerlink" title="distinct"></a>distinct</h4><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.distinct</span>(filed)</span><br></pre></td></tr></table></figure>
<ul>
<li>功能： 查看某个域的值范围</li>
</ul>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">e<span class="selector-class">.g</span>.  获取某个域的值，去重</span><br><span class="line">db<span class="selector-class">.class0</span><span class="selector-class">.distinct</span>(<span class="string">'age'</span>)</span><br></pre></td></tr></table></figure>
<h4 id="pretty"><a href="#pretty" class="headerlink" title="pretty()"></a>pretty()</h4><p>功能：格式化显示查询结果<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">e<span class="selector-class">.g</span>.</span><br><span class="line">db<span class="selector-class">.class0</span><span class="selector-class">.find</span>().pretty()</span><br></pre></td></tr></table></figure></p>
<h4 id="limit-n"><a href="#limit-n" class="headerlink" title="limit(n)"></a>limit(n)</h4><p>功能：显示前n条结果<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>. 显示查询结果前三条</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)<span class="selector-class">.limit</span>(3)</span><br></pre></td></tr></table></figure></p>
<h4 id="skip-n"><a href="#skip-n" class="headerlink" title="skip(n)"></a>skip(n)</h4><p>功能： 跳过前n条显示后面的查询结构<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>. ： 跳过前5条文档，显示后面的查询结果</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)<span class="selector-class">.skip</span>(5)</span><br></pre></td></tr></table></figure></p>
<h4 id="count"><a href="#count" class="headerlink" title="count()"></a>count()</h4><p>功能 ： 统计查询结果数量</p>
<blockquote>
<p>在统计数量时要给出一定query条件<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  统计性别为<span class="selector-tag">w</span>的文档个数</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;<span class="attribute">sex</span>:<span class="string">'w'</span>&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)<span class="selector-class">.count</span>()</span><br></pre></td></tr></table></figure></p>
</blockquote>
<h4 id="sort-field-1-1"><a href="#sort-field-1-1" class="headerlink" title="sort({field: 1/-1})"></a>sort({field: 1/-1})</h4><p>功能： 对查找结果排序<br>参数： 以键值对表示按照哪个field排序<br>       1 表示升序，-1表示降序</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.  查找结果按照降序排序</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)<span class="selector-class">.sort</span>(&#123;<span class="attribute">age</span>:-<span class="number">1</span>&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="复合排序"><a href="#复合排序" class="headerlink" title="复合排序"></a>复合排序</h4><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>. 按照年龄升序排序，年龄相同时按照姓名降序</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)<span class="selector-class">.sort</span>(&#123;<span class="attribute">age</span>:<span class="number">1</span>,name:-<span class="number">1</span>&#125;)</span><br></pre></td></tr></table></figure>
<p>函数的连续调用</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">e</span><span class="selector-class">.g</span>.</span><br><span class="line"><span class="selector-tag">db</span><span class="selector-class">.class0</span><span class="selector-class">.find</span>(&#123;&#125;,&#123;<span class="attribute">_id</span>:<span class="number">0</span>&#125;)<span class="selector-class">.sort</span>(&#123;<span class="attribute">age</span>:<span class="number">1</span>&#125;)<span class="selector-class">.limit</span>(3)</span><br></pre></td></tr></table></figure>
<p>练习：</p>
<ol>
<li><p>创建数据 名称 grade<br>use  grade</p>
</li>
<li><p>创建集合 名称 class   </p>
</li>
<li><p>集合中插入若干（5-8条即可）文档 文档格式<br>{name:’zhangsan’,age:10,sex:’m’,hobby:[‘a’,’b’]}<br>年龄范围 6-15<br>爱好选择：draw  sing  dance  basketball  football  pingpong  computer 每个同学选择2-5项</p>
<p>db.class.insert({name:’zhangsan’,age:10,sex:’m’,hobby:[‘draw’,’sing’]})</p>
</li>
<li><p>查找练习<br>查看班级所有学生信息<br>find()</p>
<p>查看班级中年龄为8岁的学生信息<br>find({age:8})</p>
<p>查看班级中年龄大于10岁学生信息<br>find({age:{$gt:10}})</p>
<p>查看班级中年龄在8-11岁之间的学生信息<br>find({age:{$gte:8,$lte:11}})</p>
<p>查看班级中年龄10岁且为男生的学生信息<br>find({age:10,sex:’m’})</p>
<p>查看班级中小于7岁或者大于14岁的学生<br>find({$or:[{age:{$lt:7}},{age:{$gt:14}}]})</p>
<p>查看班级中年龄为8岁或者11岁的学生<br>find({age:{$in:[8,11]}})</p>
<p>找到有2项兴趣爱好的学生<br>find({hobby:{$size:2}})</p>
<p>找到兴趣中 有draw的学生<br>find({hobby:’draw’})</p>
<p>找到既喜欢画画又喜欢跳舞的学生<br>find({hobby:{$all:[‘draw’,’dance’]}})</p>
<p>统计兴趣有4项的学生人数<br>find({hobby:{$size:4}}).count()</p>
<p>找出本班年龄第二大的学生<br>find().sort({age:-1}).skip(1).limit(1)</p>
<p>查看本班学生兴趣爱好涵盖哪些方面<br>db.class.distinct(‘hobby’)</p>
<p>找到年龄最大的三个学生<br>find().sort({age:-1}).limit(3)</p>
<p>删除所有年龄大于16或者小于7岁的学生除非他的爱好有三项以上<br>remove({$or:[{age:{$gt:16}},{age:{$lt:7}}],{hobby:{$size:2}}})</p>
</li>
</ol>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MongoDB/" rel="tag"># MongoDB</a>
          
            <a href="/tags/数据库/" rel="tag"># 数据库</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/08/11/mongodb/文档操作/" rel="next" title="MongoDB-文档操作">
                <i class="fa fa-chevron-left"></i> MongoDB-文档操作
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/12/mongodb/数据类型/" rel="prev" title="MongoDB-数据类型">
                MongoDB-数据类型 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#find"><span class="nav-number">1.</span> <span class="nav-text">find</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#findOne"><span class="nav-number">2.</span> <span class="nav-text">findOne</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#query更多的筛选用法"><span class="nav-number">3.</span> <span class="nav-text">query更多的筛选用法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#比较操作符"><span class="nav-number">3.1.</span> <span class="nav-text">比较操作符</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#eq-等于"><span class="nav-number">3.1.1.</span> <span class="nav-text">$eq 等于 ==</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#lt-小于-lt"><span class="nav-number">3.1.2.</span> <span class="nav-text">$lt 小于 &lt;</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#lte-小于等于-lt"><span class="nav-number">3.1.3.</span> <span class="nav-text">$lte  小于等于 &lt;=</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#gt-大于-gt"><span class="nav-number">3.1.4.</span> <span class="nav-text">$gt  大于 &gt;</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#gte-大于等于-gt"><span class="nav-number">3.1.5.</span> <span class="nav-text">$gte 大于等于 &gt;=</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ne-不等于"><span class="nav-number">3.1.6.</span> <span class="nav-text">$ne  不等于  !=</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#in-包含"><span class="nav-number">3.1.7.</span> <span class="nav-text">$in  包含</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#nin-不包含"><span class="nav-number">3.1.8.</span> <span class="nav-text">$nin 不包含</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#逻辑操作符"><span class="nav-number">3.2.</span> <span class="nav-text">逻辑操作符</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#and-逻辑与"><span class="nav-number">3.2.1.</span> <span class="nav-text">$and 逻辑与</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#or-逻辑或"><span class="nav-number">3.2.2.</span> <span class="nav-text">$or  逻辑或</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#not-逻辑非"><span class="nav-number">3.2.3.</span> <span class="nav-text">$not  逻辑非</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#nor-not-a-or-b-gt-not-a-and-not-b"><span class="nav-number">3.2.4.</span> <span class="nav-text">$nor   not  (a or b)  ===&gt; (not a) and (not b)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#逻辑条件混合"><span class="nav-number">3.2.5.</span> <span class="nav-text">逻辑条件混合</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数组-Array"><span class="nav-number">3.3.</span> <span class="nav-text">数组 Array</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#all"><span class="nav-number">3.3.1.</span> <span class="nav-text">$all</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#size"><span class="nav-number">3.3.2.</span> <span class="nav-text">$size</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#slice"><span class="nav-number">3.3.3.</span> <span class="nav-text">$slice</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其他常用查找操作符"><span class="nav-number">3.4.</span> <span class="nav-text">其他常用查找操作符</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#exists"><span class="nav-number">3.4.1.</span> <span class="nav-text">$exists</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#mod"><span class="nav-number">3.4.2.</span> <span class="nav-text">$mod</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#type"><span class="nav-number">3.4.3.</span> <span class="nav-text">$type</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#regex"><span class="nav-number">3.4.4.</span> <span class="nav-text">$regex</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查找结果的操作函数"><span class="nav-number">3.5.</span> <span class="nav-text">查找结果的操作函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#distinct"><span class="nav-number">3.5.1.</span> <span class="nav-text">distinct</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#pretty"><span class="nav-number">3.5.2.</span> <span class="nav-text">pretty()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#limit-n"><span class="nav-number">3.5.3.</span> <span class="nav-text">limit(n)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#skip-n"><span class="nav-number">3.5.4.</span> <span class="nav-text">skip(n)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#count"><span class="nav-number">3.5.5.</span> <span class="nav-text">count()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#sort-field-1-1"><span class="nav-number">3.5.6.</span> <span class="nav-text">sort({field: 1/-1})</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#复合排序"><span class="nav-number">3.5.7.</span> <span class="nav-text">复合排序</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
